package jsu.blogger.service.impl;

import jsu.blogger.filter.DataFilter;
import jsu.blogger.mapper.UserFoldersMapper;
import jsu.blogger.mapper.UserStatsMapper;
import jsu.blogger.mapper.UserTagsMapper;
import jsu.blogger.mapper.UsersMapper;
import jsu.blogger.pojo.Tag;
import jsu.blogger.service.inter.SetUserDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class SetUserDataServiceImpl implements SetUserDataService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserStatsMapper userStatsMapper;

    @Autowired
    private UserFoldersMapper userFoldersMapper;

    @Autowired
    private UserTagsMapper userTagsMapper;

    private static final Logger log = LoggerFactory.getLogger(DataFilter.class);
    @Value("${dir.userAvatarDir}")
    private  String userAvatarDir;
    @Override
    public int setUsernameByUserId(String newUsername,Long userId) {
        int i=0;
        try {
            usersMapper.updateUsernameByUserId(newUsername,userId);
            i++;
        }catch (Exception e){
            log.error(String.valueOf(e));
        }

        return i;
    }

    @Override
    public int setSexByUserId(int newSex, Long userId) {
        int i=0;
        try {
            userStatsMapper.updateSexByUserId(newSex,userId);
            i++;
        }catch (Exception e){
            log.error(String.valueOf(e));
        }

        return i;
    }

    public int setAvatarByUserId(MultipartFile avatar, Long userId) {
        int result = 0; // 默认返回值为0，表示失败
        try {
            // 获取当前工作目录
            String currentDir = System.getProperty("user.dir");
            // 构建用户头像目录的相对路径
            File targetDir = new File(currentDir, userAvatarDir);

            // 确保目标目录存在
            if (!targetDir.exists()) {
                boolean created = targetDir.mkdirs(); // 创建目录及其父目录
                if (!created) {
                    log.error(String.valueOf(new IOException("无法创建目录: " + targetDir.getAbsolutePath())));
                }
            }

            // 获取文件的原始名称并提取后缀
            String originalFilename = avatar.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.lastIndexOf(".") != -1) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 创建目标文件名（不带后缀）
            String baseFileName = String.valueOf(userId); // 例如: userAvatar123
            File targetFile = new File(targetDir, baseFileName + fileExtension); // 例如: userAvatar123.png

            // 检查是否存在同名文件（不同后缀）
            for (String ext : new String[]{".jpg", ".jpeg", ".png", ".gif"}) {
                File existingFile = new File(targetDir, baseFileName + ext);
                if (existingFile.exists()) {
                    // 删除同名但后缀不同的文件
                    boolean deleted = existingFile.delete();
                    if (!deleted) {
                        System.err.println("无法删除文件: " + existingFile.getAbsolutePath());
                    }
                }
            }

            // 将上传的文件保存到目标文件
            avatar.transferTo(targetFile);

            // 上传成功，返回1
            result = 1;
        } catch (IOException e) {
            // 使用日志记录工具记录错误
            log.error("文件上传失败: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            log.error("发生错误: " + e.getMessage());
            e.printStackTrace();
        }

        return result; // 返回结果
    }

    @Override
    public int creatFolder(Long userId, String folderName) {
        int result=0;
        try{
            userFoldersMapper.insertUserFolder(userId,folderName);
            result++;
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return result;
    }

    @Override
    public int setUserEmail(String email,long uid) {
        int i=0;
        try {
            userStatsMapper.setUserEmail(email,uid);
            i++;
        }catch (Exception e){
            System.out.println(e);
        }

        return i;
    }


    @Override
    @Transactional
    public int setUserTags(List<Tag> tagList, Long userId) {
        int re=0;
        try{
           userTagsMapper.deleteUserTagsByUserId(userId);
            for (Tag tag : tagList) {
                userTagsMapper.insertUserTags(userId, tag.getTagId());
            }
            re++;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return re;
    }


}
